<!DOCTYPE html>
<html lang="ch-CN">
<head>
    <meta charset="UTF-8">
    <title>鼠标实时位置</title>
</head>
<!--  event.clientX等不适用于有滚动条的页面中
      一般页面更适合使用pageX,可以无视滚动条的影响
-->
<style>
    body {
        margin: 0;
        padding: 0;
        width: 100%;
        height: 100vh;
        background-color: wheat;
        font-size: 30px;
        /*文本透明*/
        /*text-decoration: none;*/
        font-family: "华文楷体";
        display: flex;
        flex-direction: column;
        /*justify-content: center;*/
        align-items: center;
    }

    p {
        font-size: 40px;
        font-weight: bold;
        background-color: white;
        cursor: pointer;
    }

    #box1 {
        width: 500px;
        height: 500px;
        background-color: #b3b1af;
        border: solid 1px black;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
    }

    #box2 {
        width: 200px;
        height: 200px;
        background-color: khaki;
        border: solid 1px black;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
    }

</style>
<body id="body">
<div id="box1">
    <div id="box2">
        <p id="p">指针离盒子的位置</p>
    </div>
</div>

</body>
<script>
    function click(box,fun){
        box.onclick=fun
    }
    let box1 = document.getElementById("box1")
    let box2 = document.getElementById("box2")
    let p = document.getElementById("p")
    let body = document.body
    click(body,function (){
        alert("我是body")
    })
    click(box1,function (event){
        event = event || window.event
        // 因为box1没有关闭冒泡  所以点击box1时body也会被联想
        // event.cancelBubble = true
        alert("我是box1")
    })
    click(box2,function (event){
        event = event || window.event
        // 关闭box2的冒泡  当点击box2时 box1就不会被点击到
        event.cancelBubble = true
        alert("我是box2")
    })
    click(p,function (event){
        event = event || window.event
        event.cancelBubble = true
        alert("我是p")
    })
</script>
</html>